#include "Game.h"
#include "Field.h"
#include "Ball.h"

#include <QDebug>

Game::Game(Field &field, QObject *parent) :
	QGraphicsScene(parent), field(field)
{
	setSceneRect(0, 0, 700, 400);

	QSize size = field.getSize();
	for (int i = 0; i < size.height(); i++) {
		for (int j = 0; j < size.width(); j++) {
			if (field.isPointOnField(QPoint(j, i)) && !field.isEmptyCell(QPoint(j, i))) {
				Ball *ball = new Ball();
				addItem(ball);
				ball->setX(j * 50);
				ball->setY(i * 50);

				connect(ball, SIGNAL(moved(QPointF,QPointF,Ball*)), this, SLOT(ballMoved(QPointF,QPointF,Ball*)));
			}
		}
	}
}

void Game::ballMoved(QPointF from, QPointF to, Ball *ball)
{
	qDebug() << "moved " << from << " " << to;
	QPoint f;
	f.setY((int)((from.x() + 25) / 50));
	f.setX((int)((from.y() + 25) / 50));

	QPoint t;
	t.setY((int)((to.x() + 25) / 50));
	t.setX((int)((to.y() + 25) / 50));

	qDebug() << f << " " << t;

	if (field.makeMove(f, t)) {
		ball->setX(t.y() * 50);
		ball->setY(t.x() * 50);
	} else {
		ball->setX(f.y() * 50);
		ball->setY(f.x() * 50);
	}
}
